<?php

namespace App\Store\Controllers\Goods\GoodsSend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;


use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoods;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsLog;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsStock;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;

use App\Store\Validate\Goods\GoodsSend\GoodsSendgoods as ValidateGoodsGoodsSendGoodsSendgoods;
use Illuminate\Support\Facades\DB;

/**
 * 赠品入库
 */
class GoodsSendgoodsController extends Controller
{
    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $list = GoodsSendgoods::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsSendgoods::with(['storeinfo'])->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 新增
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only([
            'store_id', 'goods_sn_code', 'sendgoods_name',  'count', 'pieceprice', 'remark'
        ]);
        $Validate = new ValidateGoodsGoodsSendGoodsSendgoods();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $storeinfo = SiteStore::where(['id' => $req_data['store_id'], 'cp_id' => $cp_id])->first();
        if (!$storeinfo) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }
        $isexist = GoodsSendgoods::where(['cp_id' => $cp_id, 'store_id' => $req_data['store_id'], 'goods_sn_code' => $req_data['goods_sn_code']])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '货号：' . $req_data['goods_sn_code'] . '已存在']);
        }
        $maindata = $req_data;
        $maindata['cp_id'] = $cp_id;
        $maindata['sn_code'] = StoreCommon::createOrderSn();
        $maindata['create_at'] = time();
        $maindata['update_at'] = time();
        $maindata['create_account_id'] = $accountinfo['id'];
        $maindata['update_account_id'] = $accountinfo['id'];
        $maindata['create_account_real_name'] = $accountinfo['real_name'];
        $maindata['update_account_real_name'] = $accountinfo['real_name'];
        GoodsSendgoods::create($maindata);

        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }


    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only([
            'id','store_id', 'goods_sn_code', 'sendgoods_name',  'count', 'pieceprice', 'remark'
        ]);
        $Validate = new ValidateGoodsGoodsSendGoodsSendgoods('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info = GoodsSendgoods::where([['id', $req_data['id']], ['cp_id', $cp_id], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该入库单已审核']);
        }

        $isexist = GoodsSendgoods::where([['id', '<>', $req_data['id']]])->where(['cp_id' => $cp_id, 'store_id' => $req_data['store_id'], 'goods_sn_code' => $req_data['goods_sn_code']])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '货号：' . $req_data['goods_sn_code'] . '已存在']);
        }
        $maindata = $req_data;
        $maindata['update_at'] = time();
        $maindata['update_account_id'] = $accountinfo['id'];
        $maindata['update_account_real_name'] = $accountinfo['real_name'];
        GoodsSendgoods::where([['id', $req_data['id']], ['cp_id', $cp_id], ['is_del', 1]])->update($maindata);

        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 删除
     */
    public function dodel(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsSendgoods::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该入库单已审核']);
        }
        GoodsSendgoods::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['is_del'=>2,'del_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '入库单删除成功']);
    }

    /**
     * 审核
     */
    public function doauditsuccess(Request $request)
    {
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);
        $info = GoodsSendgoods::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1,'store_id'=>$store_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该入库单已审核']);
        }
        DB::beginTransaction();
        try {
            GoodsSendgoods::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>2,'audit_at'=>time()]);

            //审核后入库
            $stockinfo=GoodsSendgoodsStock::where(['cp_id' => $cp_id,'store_id' => $info->store_id,'goods_sn_code' => $info->goods_sn_code])->first();
            if($stockinfo){
                GoodsSendgoodsStock::where(['cp_id' => $cp_id,'store_id' => $info->store_id,'goods_sn_code' => $info->goods_sn_code])
                ->update(['count'=>DB::raw('count + ' . $info->count)]);
            }else{
                GoodsSendgoodsStock::create(
                    [
                    'cp_id' => $cp_id,
                    'store_id' => $info->store_id,
                    'sendgoods_name'=>$info->sendgoods_name,
                    'goods_sn_code' => $info->goods_sn_code,
                    'count'=>$info->count,
                    'pieceprice'=>$info->pieceprice,
                    'create_at'=>time(),
                    'update_at'=>time(),
                    'remark'=>$info->remark
                    ]
                );
            }
            //增加流水记录
            GoodsSendgoodsLog::create(
                [
                'cp_id' => $cp_id,
                'store_id' => 0,
                'target_store_id' => $info->store_id,
                'type'=>1,
                'sn_code'=>'',
                'sendgoods_name'=>$info->sendgoods_name,
                'goods_sn_code' => $info->goods_sn_code,
                'count'=>$info->count,
                'pieceprice'=>$info->pieceprice,
                'create_at'=>time(),
                'update_at'=>time(),
                'remark'=>$info->remark
                ]
            );
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '入库单审核成功']);
    }

    /**
     * 审核取消
     */
    public function doauditcancel(Request $request)
    {
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);
        $info = GoodsSendgoods::where(['id' => $id, 'cp_id' => $cp_id,'store_id'=>$store_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该入库单已审核']);
        }
        GoodsSendgoods::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>3,'audit_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '入库单取消成功']);
    }


    /**
     * 导入
     */
    public function doimport(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];
            $total_count=0;
            $ins_data=[];
            $return_msg=[];
            foreach ($data as $key => $val) {
                if ($key == 0) { //表头跳过
                    if(count($val)!=6){
                        return response()->json(['code' => '001', 'msg' =>'导入数据格式错误']);
                    }
                    continue;
                }
                $item=[
                    'cp_id'=>$cp_id,
                    'sn_code'=>StoreCommon::createOrderSn(),
                    'store_id'=>intval(SiteStore::where(['cp_id' => $cp_id,'store_name'=>$val[2]])->value('id')),
                    'goods_sn_code'=>$val[1],
                    'sendgoods_name'=>$val[0],
                    'count'=>$val[3]??0,
                    'pieceprice'=>$val[4]*100,
                    'remark'=>empty($val[5])? '':(string)$val[5],
                    'create_at'=>time(),
                    'update_at'=>time(),
                    'create_account_id'=>$accountinfo['id'],
                    'update_account_id'=>$accountinfo['id'],
                    'create_account_real_name'=>$accountinfo['real_name'],
                    'update_account_real_name'=>$accountinfo['real_name'],
                ];
                if($item['store_id']<=0){
                    $return_msg[]= '导入失败：门店' . $val[2] . '不存在';
                    continue;
                }

                $isexist = GoodsSendgoods::query()->where(['cp_id' => $cp_id, 'store_id' => $item['store_id'], 'goods_sn_code' => $item['goods_sn_code'],'is_del'=>1])->first();
                if ($isexist) {
                    $return_msg[]= '导入失败：条码' . $item['goods_sn_code'] . '已存在';

                    return response()->json(['code' => '001', 'msg' => '无效数据新增失败:货号'.$item['goods_sn_code'].'已存在']);
                    continue;
                }
                $total_count+=$item['count'];

               // $return_msg[]= '导入成功：条码' . $item['goods_sn_code'] . '成功导入';

                $ins_data[]=$item;

            }
            if(count($ins_data)<=0){
                return response()->json(['code' => '001', 'msg' => '无效数据新增失败']);
            }
            DB::beginTransaction();
            try {
                GoodsSendgoods::insert($ins_data);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '赠品入库导入失败' . $e->getMessage()]);
            }
            return response()->json(['code' => '000', 'msg' => '赠品入库导入成功','data'=>['return_msg'=>$return_msg]]);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在']);
        }
    }

    /**
     * 模板下载
     */
    public function downdownload(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);

        $row = [['赠品名称', '货号', '所属门店', '库存数量', '成本单价', '备注']];
        $options = [
            'C'=>SiteStore::where(['cp_id' => $cp_id])->pluck('store_name')->toArray()
        ];
        $datawith = [
            'A' => '25',
            'B' => '25',
            'C' => '25',
            'D' => '25',
            'E' => '25',
            'F' => '40',
        ];
        $filename = '赠品入库导入模板_' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $list = GoodsSendgoods::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['start_store'=>'赠品入库列表'],
            [
                'sendgoods_name' => '赠品名称',
                'goods_sn_code' => '货号',
                'store_name' => '所属门店',
                'count' => '库存数量',
                'pieceprice' => '成本单价',
                'update_account_real_name' => '更新人',
                'update_at' => '更新时间',
                'audit_status' => '状态',
                'remark' => '备注',
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'sendgoods_name' => $val['sendgoods_name'],
                'goods_sn_code' => $val['goods_sn_code'],
                'store_name' => $val['storeinfo']['store_name'],
                'count' => $val['count'],
                'pieceprice' => $val['pieceprice'] / 100,
                'update_account_real_name' => $val['update_account_real_name'],
                'update_at' => date('Y-m-d H:i:s', $val['update_at']),
                'audit_status' => $val['audit_status'] == 1 ? '待审核' : ($val['audit_status'] == 2 ? '审核' : '取消'),
                'remark' => $val['remark'],
            ];
        }

        $filename = '赠品入库信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }
}
